package menu.lt.pers.menu;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.*;
import android.widget.*;
import com.google.gson.Gson;
import menu.lt.pers.menu.Bean.RecipeBean;
import menu.lt.pers.menu.Bean.ResultByClassIdBean;
import menu.lt.pers.menu.Bean.UserBean;
import menu.lt.pers.menu.adapter.MaterialRecyclerViewAdapter;
import menu.lt.pers.menu.adapter.ProcessRecyclerViewAdapter;
import menu.lt.pers.menu.dao.CollectionDao;
import menu.lt.pers.menu.dao.HistoryDao;
import menu.lt.pers.menu.dao.SoundUtils;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class RecipeInfo extends FragmentActivity {
    //视图部分
    private ImageView imageviewPic; //菜品图片地址
    private TextView tvName;//菜品的名字
    private TextView tvPreparetime;//菜品准备时间
    private TextView tvCookingtime;//菜品烹饪时间
    private TextView tvPeoplenum;//菜品用餐人数
    private TextView tvContent;//菜品简介
    private RecyclerView recyclerView_process;
    private RecyclerView recyclerView_material;
    //适配器
    private MaterialRecyclerViewAdapter materialAdapter;
    private ProcessRecyclerViewAdapter processAdapter;
    //布局管理器
    private LinearLayoutManager processManager;
    private LinearLayoutManager materialManager;
    //数据部分
    private Bitmap headBitMap;//存储菜品图片
    private UserBean user;
    private boolean login_state = false;

    private ResultByClassIdBean.ResultBean.ListBean recipe;//菜品
    private List<ResultByClassIdBean.ResultBean.ListBean.MaterialBean> materials;//需要材料
    private List<ResultByClassIdBean.ResultBean.ListBean.ProcessBean> processes;//烹饪方法

    private CollectionDao collectionDao;
    private HistoryDao historyDao;
    private RecipeBean recipeBean;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_info);
        initView();
        initData();
        updateView();
        SoundUtils.init(RecipeInfo.this);
    }
    private void initView() {
        imageviewPic =  findViewById(R.id.imageview_pic);
        tvName =  findViewById(R.id.tv_name);
        tvPreparetime =  findViewById(R.id.tv_preparetime);
        tvCookingtime =  findViewById(R.id.tv_cookingtime);
        tvPeoplenum =  findViewById(R.id.tv_peoplenum);
        tvContent =  findViewById(R.id.tv_content);
        recyclerView_process = findViewById(R.id.recyclerView_process);
        recyclerView_material = findViewById(R.id.recycleView_material);
    }
    private void initData() {
        String str = getIntent().getStringExtra("recipe"); //获取传过来的字符串数据
        Gson gson = new Gson();
        recipe = gson.fromJson(str,ResultByClassIdBean.ResultBean.ListBean.class);//将字符串转化为对象
        String userStr = getIntent().getStringExtra("user");
        if (userStr!=null){
            Log.i("RecipeInfo.initData", "initData: "+userStr);
            login_state = true;
            user = new UserBean();
            user = gson.fromJson(userStr, UserBean.class);
        } else {user = new UserBean();Log.i("RecipeInfo.initData", "initData: "+"未登录");}

        materials = recipe.getMaterial();//获取菜品中的材料列表
        processes = recipe.getProcess();//获取菜品中的过程列表
        materialAdapter = new MaterialRecyclerViewAdapter(RecipeInfo.this,materials);//初始化适配器
        processAdapter = new ProcessRecyclerViewAdapter(RecipeInfo.this,processes);//初始化适配器

        materialManager = new LinearLayoutManager(this);//初始化布局管理器
        materialManager.setOrientation(LinearLayout.VERTICAL);//设置垂直布局
        materialManager.setSmoothScrollbarEnabled(false);
        recyclerView_material.setLayoutManager(materialManager);//recyclerView_material设置布局管理器

        processManager = new LinearLayoutManager(this);//初始化布局管理器
        processManager.setOrientation(LinearLayout.VERTICAL);//设置垂直布局
        materialManager.setSmoothScrollbarEnabled(false);
        recyclerView_process.setLayoutManager(processManager);//recyclerView_process设置布局管理器

        recipeBean = new RecipeBean();
        collectionDao = new CollectionDao(RecipeInfo.this);
        //将数据换成能够存入数据库额bean
        getRecipeBean();
        addHistory();
    }
    //更新视图
    private void updateView() {
        if (recipe!=null){
            new GetBimap().execute(recipe.getPic(),"recipe_pic");
            //如果 hashmap没有头像数据，那么设置为默认头像
            if (headBitMap==null){ imageviewPic.setImageResource(R.drawable.timg); }
            //字符串去杂
            String[] strArr = recipe.getContent().split("<br />");
            String str_content = "  ";
            for (int i=0;i<strArr.length;i++){ str_content = str_content.concat(strArr[i]+"\n"); }

            //更改视图
            tvContent.setText(str_content);
            tvName.setText(recipe.getName());
            tvCookingtime.setText(recipe.getCookingtime());
            tvPeoplenum.setText(recipe.getPeoplenum());
            tvPreparetime.setText(recipe.getPreparetime());
            recyclerView_process.setAdapter(processAdapter);
            recyclerView_material.setAdapter(materialAdapter);

        }
    }
    class GetBimap extends AsyncTask {
        private String key;
        @Override
        protected Bitmap doInBackground(Object[] params) {
            key = (String) params[1];
            if (headBitMap == null){
                String uripath = (String) params[0];
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(5000, TimeUnit.SECONDS)
                        .readTimeout(5000,TimeUnit.SECONDS)
                        .build();
                Request request = new Request.Builder()
                        .url(uripath)
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()){
                        InputStream inputStream = response.body().byteStream();//得到图片的流
                        Bitmap bitmapfromNet = BitmapFactory.decodeStream(inputStream);
                        return bitmapfromNet;
                    }else {
                        Log.i("Class.getBimap.else", recipe.getName()+" 获取失败 "+String.valueOf(params[0]));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            if (o!=null){
                headBitMap = (Bitmap) o;
                if (key.equals("recipe_pic")){
                    imageviewPic.setImageBitmap(headBitMap);//更换菜品图片
                }
            }
        }
    }
    //收藏功能
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = new MenuInflater(RecipeInfo.this);
        inflater.inflate(R.menu.recipe_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item_collect:
                Log.i("RecipeInfo.onOptionsItemSelected", "onOptionsItemSelected: "+login_state);
                if (login_state){
                    collectionDao.insert(recipeBean);
                } else {
                    Intent intent = new Intent(RecipeInfo.this,LoginActivity.class);
                    startActivity(intent);
                }

                SoundUtils.boom();
                break;
            default:
                Toast.makeText(RecipeInfo.this, "选择错误", Toast.LENGTH_LONG).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    public void addHistory(){
        if (login_state){
            historyDao = new HistoryDao(this);
            historyDao.insert(recipeBean);
        }
    }
    public void getRecipeBean(){
        if (login_state){
            RecipeBean bean = new RecipeBean();
            Gson gson = new Gson();
            bean.setClassid(recipe.getClassid());
            bean.setName(recipe.getName());
            bean.setPeoplenum(recipe.getPeoplenum());
            bean.setPreparetime(recipe.getPreparetime());
            bean.setCookingtime(recipe.getCookingtime());
            bean.setContent(recipe.getContent());
            bean.setPic(recipe.getPic());
            bean.setTag(recipe.getTag());
            bean.setMaterialJson(gson.toJson(recipe.getMaterial()));
            bean.setProcessJson(gson.toJson(recipe.getProcess()));
            bean.setUserid(user.getId());
            this.recipeBean = bean;
        }
    }
}
